package pub.gll.onepeas.libbase.util

import android.text.InputFilter
import android.text.SpannableStringBuilder
import android.text.Spanned

class SymbolInputFilter private constructor(filterChars: CharArray?) : InputFilter {
    private val filterChars: CharArray = filterChars ?: CharArray(0)

    /**
     * @param source 输入的文字
     * @param start  输入-0，删除-0
     * @param end    输入-文字的长度，删除-0
     * @param dest   原先显示的内容
     * @param dstart 输入-原光标位置，删除-光标删除结束位置
     * @param dend   输入-原光标位置，删除-光标删除开始位置
     * @return null表示原始输入，""表示不接受输入，其他字符串表示变化值
     */
    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence {
        if (dstart == 0) {
            if (needFilter(source)) {
                val builder = SpannableStringBuilder()
                var abStart = start
                for (i in start until end) {
                    if (isFilterChar(source[i])) {
                        if (i != abStart) {
                            builder.append(source.subSequence(abStart, i))
                        }
                        abStart = i + 1
                    }
                }
                if (abStart < end) {
                    builder.append(source.subSequence(abStart, end))
                }
                return builder
            }
        } else {
            return source
        }
        return source
    }

    private fun needFilter(source: CharSequence): Boolean {
        val s = source.toString()
        for (filterChar in filterChars) {
            if (s.indexOf(filterChar) >= 0) {
                return true
            }
        }
        return false
    }

    private fun isFilterChar(c: Char): Boolean {
        for (filterChar in filterChars) {
            if (filterChar == c) {
                return true
            }
        }
        return false
    }

    companion object {
        const val TAG = "SymbolInputFilter"
        fun newlineCharFilter(): SymbolInputFilter {
            return SymbolInputFilter(charArrayOf('\n'))
        }

        fun whitespaceCharFilter(): SymbolInputFilter {
            return SymbolInputFilter(charArrayOf(' '))
        }

        fun returnCharFilter(): SymbolInputFilter {
            return SymbolInputFilter(charArrayOf('\r'))
        }

        fun wnrCharFilter(): SymbolInputFilter {
            return SymbolInputFilter(charArrayOf(' ', '\n', '\r'))
        }
    }

}